const express = require('express')


const app = express()

const cors = require('cors')
const sendUtil = require('./utils/sendUtil')
const joi = require('joi')

//导入路由
const route = require('./router')

app.use(express.json())
app.use(express.urlencoded())

app.use(cors())

//优化send代码
app.use(sendUtil)

// 托管静态资源文件
app.use('/uploads', express.static('./uploads'))


//载入路由，让用户访问
app.use(route)

//

//错误中间件
app.use(function(err, req, res, next){
  if(err instanceof joi.ValidationError) return res.cc(err)
  //捕获身份认证失败的错误
  if(err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
  //未知错误
  return res.cc(err)
})

const PORT = 3000

app.listen(PORT, (req, res)=>{
  console.log(`server running at http://localhost:${PORT}`)
})